<template>
  <el-dialog v-model="mapStore.addDialogVisible" :title="mapStore.openType === 'edit' ? '编辑人员' : '新增人员'" width="500"
    destroy-on-close top="100px" :draggable="true" :close-on-click-modal="false" @closed="handleClose(ruleFormRef)">
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="mapStore.ruleAddForm" :rules="rules" label-width="auto"
      :size="formSize" status-icon>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="mapStore.ruleAddForm.name" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="身份证号" prop="IDNumber">
        <el-input v-model="mapStore.ruleAddForm.IDNumber" placeholder="请输入身份证号" />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="mapStore.ruleAddForm.sex" placeholder="请输入性别">
          <el-option label="男" value="man" />
          <el-option label="女" value="female" />
        </el-select>
      </el-form-item>
      <el-form-item label="车牌号" prop="licensePlateNumber">
        <el-input v-model="mapStore.ruleAddForm.licensePlateNumber" placeholder="请输入车牌号" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="mapStore.ruleAddForm.phone" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="居住地址" prop="address">
        <el-input v-model="mapStore.ruleAddForm.address" placeholder="请输入居住地址" />
      </el-form-item>
      <el-form-item label="相片" style="margin-bottom: 0; padding-bottom: 0; height: 26px">
        <div class="file-upload-wrapper">
          <div class="file-upload-in">
            <form id="file-form">
              <input type="file" name="" class="file-upload-input" id="file-upload-id" size="28" @change="checkFile"
                ref="fileInputRef" />
            </form>
            <div class="file-upload-name">{{ fileUploadName }}</div>
            <label for="file-upload-id" class="file-upload-label">选择</label>
            <label class="file-cancel-label" @click="cancelCheckFile">取消</label>
          </div>
        </div>
      </el-form-item>
      <el-form-item label=" ">
        <div class="file-upload-tips">{{ fileUploadTips }}</div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          {{ mapStore.openType === "edit" ? "编辑" : "新增" }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { getAjaxTableData } from "@/api/getAjaxData.js";
import pinia from "@/store/pinia";
import { useMapStore } from "@/store/map";
const mapStore = useMapStore(pinia);

const formSize = ref("default");
const fileInputRef = ref(null);
const ruleFormRef = ref();
let fileUploadName = ref("");
let fileUploadTips = ref("");

const rules = reactive({
  name: [{ required: true, trigger: "blur", message: "请输入姓名" }],
  IDNumber: [{ required: true, validator: checkIDNumber, trigger: "blur" }],
  sex: [{ required: true, trigger: "change", message: "请选择性别" }],
  licensePlateNumber: [
    { required: true, trigger: "blur", message: "请输入车牌号" },
  ],
  phone: [{ required: true, trigger: "blur", message: "请输入手机号" }],
  address: [{ required: true, trigger: "blur", message: "请输入地址" }],
});

function checkIDNumber(rule, value, callback) {
  if (value.length === 0) {
    callback(new Error("请输入身份证号"));
  } else if (
    !/^[1-9]\d{5}(18|19|(\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(
      value
    )
  ) {
    callback(new Error("请输入格式正确的身份证号"));
  } else {
    callback();
  }
}

function checkFileType(file) {
  const index = file.lastIndexOf(".");
  return file.substring(index);
}

function checkFile() {
  const file = fileInputRef.value.files[0];
  if (file) {
    const fileType = checkFileType(file.name);
    fileUploadName.value = file.name;
    if ([".png", ".gif", ".jpg", ".jpeg", ".webp"].indexOf(fileType) < 0) {
      document.querySelector(".file-upload-name").style.borderColor = "#FF0000";
      fileUploadTips.value = "请选择.png/.jpg/.jpeg/.gif/.webp类型图片文件";
      // document.getElementById("file-form").reset();
      return false;
    } else if (file.size > 1024 * 1024 * 10) {
      document.querySelector(".file-upload-name").style.borderColor = "#FF0000";
      fileUploadTips.value = "图片文件不能大于10M";
      // document.getElementById("file-form").reset();
      return false;
    }
    fileUploadTips.value = "";
    document.querySelector(".file-upload-name").style.borderColor = "#dcdfe6";
    return true;
  }

  return true;
}

function cancelCheckFile() {
  document.querySelector(".file-upload-name").style.borderColor = "#dcdfe6";
  fileUploadName.value = "";
  fileUploadTips.value = "";
  document.getElementById("file-form").reset();
}

function resetFieldsValue(formEl) {
  if (!formEl) return;
  formEl.resetFields();
  for (const prop in mapStore.ruleAddForm) {
    if (mapStore.ruleAddForm.hasOwnProperty(prop)) {
      mapStore.ruleAddForm[prop] = "";
    }
  }
  document.getElementById("file-form").reset();
  document.querySelector(".file-upload-name").style.borderColor = "#dcdfe6";
  fileUploadName.value = "";
  fileUploadTips.value = "";
}

const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      let url;

      if (mapStore.openType === "add") {
        url = "/WordTool/word/maintain/form";
      } else {
        url = "/WordTool/word/maintain/update";
      }

      if (!checkFile()) return;

      const formData = new FormData();
      formData.append("name", mapStore.ruleAddForm.name);
      formData.append("IDNumber", mapStore.ruleAddForm.IDNumber);
      formData.append("sex", mapStore.ruleAddForm.sex);
      formData.append(
        "licensePlateNumber",
        mapStore.ruleAddForm.licensePlateNumber
      );
      formData.append("phone", mapStore.ruleAddForm.phone);
      formData.append("address", mapStore.ruleAddForm.address);

      if (fileInputRef.value.files[0]) {
        formData.append("photoFile", fileInputRef.value.files[0]);
      }

      console.log("formData");
      console.log(formData);

      // begin
      axios
        .post(url, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then(
          (resp) => {
            if (resp.data.status === "OK") {
              resetFieldsValue(formEl);
              mapStore.addDialogVisible = false;
            } else {
              ElMessage({
                message: resp.data.message,
                type: "error",
              });
            }
          },
          (err) => {
            console.log(err);
          }
        );
      // end
    } else {
      // ElMessage.error("fields");
      checkFile();
    }
  });
};

function resetForm(formEl) {
  if (!formEl) return;
  resetFieldsValue(formEl);
  mapStore.addDialogVisible = false;
}

function handleClose(formEl) {
  if (!formEl) return;
  resetFieldsValue(formEl);
}
</script>

<style>
@import url("@/assets/main.css");

.file-upload-wrapper {
  display: flex;
  height: auto;
  padding-bottom: 20px;
  width: 100%;
}

.file-upload-in {
  flex: 1;
  height: 31px;
  display: flex;
}

.file-upload-input {
  display: none;
}

.file-upload-label {
  display: block;
  padding: 5px 10px;
  height: 31px;
  line-height: 20px;
  background-color: #339933;
  color: white;
  cursor: pointer;
  box-shadow: 1px 1px 1px #ccc;
  border-right: 1px solid #ccc;
}

.file-upload-label:hover {
  background-color: #529b2e;
}

.file-cancel-label {
  display: block;
  padding: 5px 10px;
  height: 31px;
  line-height: 20px;
  background-color: #339933;
  color: white;
  cursor: pointer;
  box-shadow: 1px 1px 1px #ccc;
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
}

.file-cancel-label:hover {
  background-color: #529b2e;
}

.file-upload-name {
  flex: 1;
  line-height: 30px;
  font-size: 14px;
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
  border-top-width: 1.5px;
  border-right-width: 0;
  border-bottom-width: 1px;
  border-left-width: 1px;
  border-color: #dcdfe6;
  border-style: solid;
  padding-left: 10px;
  overflow: hidden;
}

.file-upload-tips {
  color: #f56c6c;
  font-size: 12px;
  height: 20px;
  line-height: 20px;
}
</style>
